#pragma once

#include "Any.h"
#include "Semaphare.h"
#include <atomic>
#include <memory>

class Task; // 前置声明

class Result : public std::enable_shared_from_this<Result> {
public:
  ~Result() = default;

  void setVal(Any any) {
    any_ = std::move(any);
    sem_.post();
  }

  Any get() {
    if (!isValid_) {
      throw std::runtime_error("task submit failed");
    }
    sem_.wait();
    return std::move(any_);
  }

  void bindTask();

  static std::shared_ptr<Result> make_Result(std::shared_ptr<Task> task,
                                             bool isValid = true);

private:
  Result(std::shared_ptr<Task> task, bool isValid = true)
      : task_(std::move(task)), isValid_(isValid) {}

  Any any_{};
  Semaphare sem_{};
  std::shared_ptr<Task> task_;
  std::atomic_bool isValid_;
};